package org.aisino.shdzfp.vistool.swing;

import java.awt.Color;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;

import org.aisino.shdzfp.vistool.exception.NullXmlException;
import org.aisino.shdzfp.vistool.util.XmlFormatUtil;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;

public class XmlReader extends JPanel {

	private final static Logger log = Logger.getLogger(XmlReader.class);

//	private JRadioButton radioButtonIssue;
//	private JRadioButton radioButtonDownload;
//	private JRadioButton radioButtonDetailDownload;
	private JCheckBox boxNumber;
	private JButton buttonCheck;
	private JButton buttonReset;
	private JButton buttonCopy;
	private ButtonGroup buttonGroup;
	private JTextArea areaOrigin;
	// private JTextArea areaResult;
	private JTextPane areaResult;
	private JTextArea[] areas;
	private String[] COLORSTYLE;
	private int COLORS = 7;

	public XmlReader() {
		paint();
		otherInit();
		setMonitor();
	}

	private void otherInit() {
		// areas = new JTextArea[2];
		// areas[0] = areaOrigin;
		// areas[1] = areaResult;

		Style def = areaResult.getStyledDocument().addStyle(null, null);
		StyleConstants.setFontFamily(def, "verdana");
		StyleConstants.setFontSize(def, 10);
		Style normal = areaResult.addStyle("normal", def);
		Style red = areaResult.addStyle("red", normal);
		StyleConstants.setForeground(red, Color.RED);
		Style green = areaResult.addStyle("green", normal);
		StyleConstants.setForeground(green, Color.GREEN);
		Style blue = areaResult.addStyle("blue", normal);
		StyleConstants.setForeground(blue, Color.BLUE);
		Style cyan = areaResult.addStyle("cyan", normal);
		StyleConstants.setForeground(cyan, Color.CYAN);
		Style yellow = areaResult.addStyle("yellow", normal);
		StyleConstants.setForeground(yellow, Color.YELLOW);
		Style pink = areaResult.addStyle("pink", normal);
		StyleConstants.setForeground(pink, Color.PINK);
		Style orange = areaResult.addStyle("orange", normal);
		StyleConstants.setForeground(orange, Color.ORANGE);

		COLORSTYLE = new String[COLORS];
		COLORSTYLE[0] = "red";
		COLORSTYLE[1] = "green";
		COLORSTYLE[2] = "blue";
		COLORSTYLE[3] = "cyan";
		COLORSTYLE[4] = "yellow";
		COLORSTYLE[5] = "pink";
		COLORSTYLE[6] = "orange";

		areaResult.setParagraphAttributes(normal, true);
	}

	private void paint() {
		this.setLayout(null);

		int margin = 5;

		int marginX = 5;
		int marginY = 5;
		int widthOrigin = 632;
		int heightOrigin = 80;

		int currX = marginX;
		int currY = marginY;
		int moduleY = heightOrigin;
		// module a
		areaOrigin = new JTextArea();
		JScrollPane scrollPlainText = new JScrollPane(areaOrigin);
		scrollPlainText.setBounds(currX, currY, widthOrigin, heightOrigin);
		scrollPlainText.setAutoscrolls(true);
		add(scrollPlainText);

		// module b
		currY += (moduleY);
		int radioX = 75;
		int radioY = 30;
		moduleY = radioY;
//		radioButtonIssue = new JRadioButton("FPKJ", true);
//		radioButtonIssue.setBounds(currX = marginX, currY, radioX, radioY);
//		radioButtonDownload = new JRadioButton("FPXZ");
//		radioButtonDownload.setBounds(currX += radioX, currY, radioX, radioY);
//		radioButtonDetailDownload = new JRadioButton("MXXZ");
//		radioButtonDetailDownload.setBounds(currX += radioX, currY, radioX, radioY);
		boxNumber = new JCheckBox("Number");
		boxNumber.setBounds(currX = marginX, currY, radioX * 3, radioY);

		buttonGroup = new ButtonGroup();
//		buttonGroup.add(radioButtonIssue);
//		buttonGroup.add(radioButtonDownload);
//		buttonGroup.add(radioButtonDetailDownload);
//		add(radioButtonIssue);
//		add(radioButtonDownload);
//		add(radioButtonDetailDownload);
		add(boxNumber);
		
		int buttonX = 130;
		int buttonY = 30;
		buttonCheck = new JButton("Check");
		buttonReset = new JButton("Reset");
		buttonCheck.setBounds(currX += (radioX * 3 + margin), currY, buttonX, buttonY);
		buttonReset.setBounds(currX += (buttonX + margin), currY, buttonX, buttonY);
		add(buttonCheck);
		add(buttonReset);

		int longButtonX = 130;
		int longButtonY = buttonY;
		buttonCopy = new JButton("Copy");
		buttonCopy.setBounds(currX += (buttonX + margin), currY, longButtonX, longButtonY);
		add(buttonCopy);

		// module c
		int widthOrigin2 = widthOrigin;
		int heightOrigin2 = 280;
		currY += (moduleY + margin);
		// areaResult = new JTextArea(10, 60);
		areaResult = new JTextPane();
		JScrollPane scrollResult = new JScrollPane(areaResult);
		scrollResult.setBounds(currX = marginX, currY, widthOrigin2, heightOrigin2);
		scrollResult.setAutoscrolls(true);
		add(scrollResult);

	}

	private void broadcastError(String msg) {
		try {
			areaResult.getDocument().insertString(0, msg, areaResult.getStyle("red"));
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void broadcastInfo(String msg) {
		try {
			areaResult.getDocument().insertString(0, msg, areaResult.getStyle("black"));
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void cleanArea() {
		// for(JTextArea area : areas) {
		// area.setText("");
		// }
		areaOrigin.setText("");
		areaResult.setText("");
	}

	private void setMonitor() {

		buttonReset.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				cleanArea();
			}
		});

		buttonCopy.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				StringSelection stsel = new StringSelection(areaResult.getText());
				Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
			}
		});

		buttonCheck.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				try {
					areaResult.setText("");
					
					if("".equals(areaOrigin.getText().trim())) {
						return ;
					}
					
					String xml = XmlFormatUtil.format(areaOrigin.getText());
					
					String[] metas = XmlFormatUtil.getMeta(xml);

					colorDispose(metas, boxNumber.isSelected());
				} catch (NullXmlException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (DocumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					broadcastError("ERROR : " + e1.getMessage());
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (BadLocationException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});

	}

	private void colorDispose(String[] metas, boolean numberFlag) throws BadLocationException {
		if (metas == null) {
			return;
		}
		for (String meta : metas) {
			int i = (meta.length() - meta.trim().length()) / 2;
			if (meta.matches("[\\s\\S]+>[\\s\\S]+<[\\s\\S]+")) {
				int firstGt = meta.indexOf(">");
				int secondLt = meta.indexOf("<", firstGt + 1);
				String head = meta.substring(0, firstGt + 1);
				areaResult.getDocument().insertString(areaResult.getDocument().getLength(), !numberFlag ? head : i + " " + head,
						areaResult.getStyle(COLORSTYLE[i % COLORS]));
				String body = meta.substring(firstGt + 1, secondLt);
				areaResult.getDocument().insertString(areaResult.getDocument().getLength(), body,
						areaResult.getStyle("normal"));
				String tail = meta.substring(secondLt);
				areaResult.getDocument().insertString(areaResult.getDocument().getLength(), tail + "\n",
						areaResult.getStyle(COLORSTYLE[i % COLORS]));
			} else {
				areaResult.getDocument().insertString(areaResult.getDocument().getLength(), !numberFlag ? meta + "\n" : i + " " + meta + "\n",
						areaResult.getStyle(COLORSTYLE[i % COLORS]));
			}
		}
	}

}
